import { type RemoveMethods } from "@/types/remove-methods";
import { YearMemory } from "@model/Memory";
import { TaskLogData } from "@model/TaskLogMap";
import UseSetting from "@pinias/UseSetting";
import pinia from "@pinias/pinia";
import { changeTimeUnit, DateTimeStr, getMonth, getWeek, getYear } from "@utils/DateUtils";
import { statisticPath } from "@utils/pathUtils";

export class IdStat {
  id: string;
  fatherId: number; // 用于已归档的任务的父id：阶段id
  everyDayLogMap: Map<string, Array<string>>; // 20230723:[20230723003406,...]
  everyMonthLogMap: Map<string, Array<string>>; // 202307:[20230723,20230724]
  everyDayTakeTime: Map<string, number>; // 20230723: 120...
  everyMonthMemoryMap: Map<string, Array<string>>; // 202307:[20230723003406,...],列表需要顺序排列

  constructor(id: string) {
    this.id = id;
    this.everyDayLogMap = new Map<string, Array<string>>();
    this.everyMonthLogMap = new Map<string, Array<string>>();
    this.everyDayTakeTime = new Map<string, number>();
    this.everyMonthMemoryMap = new Map<string, Array<string>>();
    this.fatherId = 0;
  }
}
const { getCacheModel } = UseSetting(pinia);
export class CacheIdStatMap {
  cacheIdStatList: Array<string>; // id.json
  IdStatMap: Map<string, IdStat>; //id:IdStat
  changeKeys: Array<string>; // id,...

  setInfo(data: RemoveMethods<CacheIdStatMap>) {
    Object.assign(this, data);
  }
  async getTakeTime4Stat(chooseIds: Array<number>, timeStamp: number, type: string) {
    const series = new Array<{ id: number; name: string; takeTimeList: Array<number> }>();
    let timeRange = new Array<number>();
    let timeRangeStr = new Array<string>();
    if (type === "周" || type === "月") {
      if (type === "月") timeRange = getMonth(timeStamp);
      else timeRange = getWeek(timeStamp);
      // console.log(timeRange.map(value=>timestampToDateTime(value)),"++++++++++++++++++")

      for (const chooseId of chooseIds) {
        const stat = await this.getIdStatNotCreate(chooseId);
        const takeTimeList = new Array<number>();
        for (const number of timeRange) {
          const timeDateStr = new DateTimeStr(number);
          let takeTime = stat?.everyDayTakeTime.get(timeDateStr.getDayInfo());
          if (takeTime === undefined) takeTime = 0;
          takeTimeList.push(takeTime);
        }
        const model = { id: chooseId, name: "", takeTimeList: takeTimeList };
        series.push(model);
      }
      timeRangeStr = timeRange.map(value => new DateTimeStr(value).getDayInfo());
    }
    if (type === "年") {
      timeRange = getYear(timeStamp);
      // console.log(timeRange.map(value=>timestampToDateTime(value)),"++++++++++++++++++")
      for (const chooseId of chooseIds) {
        const stat = await this.getIdStatNotCreate(chooseId);
        const takeTimeList = new Array<number>();
        for (const number of timeRange) {
          const timeDateStr = new DateTimeStr(number);
          let takeTime = 0;
          if (stat !== undefined) {
            const monthLogMap = stat.everyMonthLogMap.get(timeDateStr.getMonthInfo());
            if (monthLogMap !== undefined) {
              for (const string of monthLogMap) {
                const t = stat.everyDayTakeTime.get(string);
                if (t !== undefined) takeTime += t;
              }
            }
          }
          takeTimeList.push(takeTime);
        }
        const model = { id: chooseId, name: "", takeTimeList: takeTimeList };
        series.push(model);
      }
      timeRangeStr = timeRange.map(value => new DateTimeStr(value).getMonthInfo());
    }
    return { timeRange: timeRangeStr, series: series };
  }
  async getTakeTime(id: number | string, timeRangeTimeStamp: Array<number>) {
    let allTime = 0;
    const stat = await this.getIdStatNotCreate(id);
    // if (stat === undefined) {
    //   const fileName = id.toString() + ".json";
    //   const file = this.cacheIdStatList.find(value => value === fileName);
    //   // console.log(stat,"getTakeTime",id,this,fileName,file)
    //   if (file !== undefined) {
    //     // 说明有保存
    //     stat = await this.getIdStat(id);
    //   }
    // }
    if (stat !== undefined) {
      if (timeRangeTimeStamp === undefined || timeRangeTimeStamp.length !== 2) {
        //获取全部时间
        const everryDayMap = stat.everyDayTakeTime;
        for (const everryDayMapElement of everryDayMap) {
          allTime += everryDayMapElement[1];
        }
      } else {
        // 获取区域内时间
      }
    }
    return changeTimeUnit(allTime);
  }
  async getIdStatNotCreate(id: number | string) {
    let stat = this.IdStatMap.get(id.toString());
    if (stat === undefined) {
      const fileName = id.toString() + ".json";
      const file = this.cacheIdStatList.find(value => value === fileName);
      // console.log(stat,"getTakeTime",id,this,fileName,file)
      if (file !== undefined) {
        // 说明有保存
        stat = await this.getIdStat(id);
      }
    }
    return stat;
  }
  async getIdStat(id: number | string) {
    // 获取数据库记录，：如果超过年份，则创建文件
    const key = id.toString();
    let idStat = new IdStat(key);
    // console.log(endTime)
    idStat = await getCacheModel(statisticPath + key + ".json", key, this.IdStatMap, idStat);
    return idStat;
  }

  async getMemory4MonthList(monthRageTimeStamp: Array<number>, ids: Array<number>) {
    const result = new Array<string>();
    for (const id of ids) {
      const idStat = await this.getIdStatNotCreate(id);
      const monthMap = idStat?.everyMonthMemoryMap;
      if (monthMap !== undefined && monthMap.size > 0) {
        for (const timeStamp of monthRageTimeStamp) {
          const timeStr = new DateTimeStr(timeStamp);
          const monthKey = timeStr.getMonthInfo();
          const taskLogIds = monthMap.get(monthKey);
          if (taskLogIds !== undefined && taskLogIds.length > 0) {
            for (const taskLogId of taskLogIds) {
              YearMemory.add2SortList(taskLogId, result);
            }
          }
        }
      }
    }
    return result;
  }

  deleteMemory(taskLogData: Array<TaskLogData>, idStat: IdStat) {
    for (let i = 0; i < taskLogData.length; i++) {
      const log = taskLogData[i];
      const dayKey = log.id.slice(0, 6);
      let list = idStat.everyMonthMemoryMap.get(dayKey);
      if (list === undefined) {
        list = [];
        idStat.everyMonthMemoryMap.set(dayKey, list);
      }
      list = list.filter(value => value !== log.id);
      idStat.everyMonthMemoryMap.set(dayKey, list);
    }
  }
  addMemory(taskLogData: Array<TaskLogData>, idStat: IdStat) {
    for (let i = 0; i < taskLogData.length; i++) {
      const log = taskLogData[i];
      if (log.isMemory) {
        const dayKey = log.id.slice(0, 6);
        let list = idStat.everyMonthMemoryMap.get(dayKey);
        if (list === undefined) {
          list = [];
          idStat.everyMonthMemoryMap.set(dayKey, list);
        }
        YearMemory.add2SortList(log.id, list);
      }
    }
  }

  constructor(cacheIdStatList: Array<string>, IdStatMap: Map<string, IdStat>, changeKeys: Array<string>) {
    this.cacheIdStatList = cacheIdStatList;
    this.IdStatMap = IdStatMap;
    this.changeKeys = changeKeys;
  }

  async changeTaskFatherId(newStageId: number, taskIds: Array<number>) {
    const changeKeys = new Set<string>();
    for (const taskId of taskIds) {
      const stat = await this.getIdStat(taskId);
      stat.fatherId = newStageId;
      changeKeys.add(taskId.toString());
    }
    this.changeKeys = [...changeKeys];
  }

  async changeTaskLogData4Stat(
    beforeTaskLogdata: Array<TaskLogData>,
    beforeTaskIds: Array<number | undefined>,
    afterTaskLogdata: Array<TaskLogData>,
    afterTaskIds: Array<number | undefined>,
  ) {
    const changeKey = new Set<string>();
    if (!(beforeTaskLogdata === undefined || beforeTaskLogdata.length === 0)) {
      for (let j = 0; j < beforeTaskIds.length; j++) {
        const beforeTaskId = beforeTaskIds[j];
        if (beforeTaskId !== undefined && beforeTaskId > 0) {
          const key = beforeTaskId.toString();
          let beforeIdStat = new IdStat(key);
          // console.log(endTime)
          beforeIdStat = await getCacheModel(statisticPath + key + ".json", key, this.IdStatMap, beforeIdStat);
          // console.log("changeTaskLogData2NewTaskId", beforeIdStat);
          if (beforeIdStat !== undefined) {
            for (let i = 0; i < beforeTaskLogdata.length; i++) {
              const log = beforeTaskLogdata[i];
              const dayKey = log.id.slice(0, 8);
              let list = beforeIdStat.everyDayLogMap.get(dayKey);
              // console.log("list", dayKey, beforeIdStat.everyDayLogMap, list);
              if (list != undefined) {
                list = list.filter(value => value !== log.id);
                // const index = list.findIndex(value => value===log.id);
                // if(index > 0) list.splice(index,1)
                beforeIdStat.everyDayLogMap = beforeIdStat.everyDayLogMap.set(dayKey, [...list]);
              }
              // console.log("list", dayKey, beforeIdStat.everyDayLogMap, list, log.id);
              let takeTime = log.startTime - log.endTime;
              const takeTime2 = beforeIdStat.everyDayTakeTime.get(dayKey);
              if (takeTime2 !== undefined) {
                takeTime += takeTime2;
                // console.log(takeTime);
                beforeIdStat.everyDayTakeTime = beforeIdStat.everyDayTakeTime.set(dayKey, takeTime);
                // console.log(beforeIdStat.everyDayTakeTime);
                // console.log(beforeIdStat);
              }
            }
            // 删除回忆
            this.deleteMemory(beforeTaskLogdata, beforeIdStat);
            changeKey.add(key);
            // console.log("changeTaskLogData2NewTaskId", beforeIdStat, key);
            // this.changeKeys.push(key);
          }
        }
      }
    }
    if (!(afterTaskLogdata === undefined || afterTaskLogdata.length === 0)) {
      for (let j = 0; j < afterTaskIds.length; j++) {
        const afterTaskId = afterTaskIds[j];
        if (afterTaskId !== undefined && afterTaskId > 0) {
          const key = afterTaskId.toString();
          let beforeIdStat = new IdStat(key);
          // console.log(endTime)
          beforeIdStat = await getCacheModel(statisticPath + key + ".json", key, this.IdStatMap, beforeIdStat);
          // console.log("beforeIdStat", beforeIdStat);
          if (beforeIdStat !== undefined) {
            for (let i = 0; i < afterTaskLogdata.length; i++) {
              const log = afterTaskLogdata[i];
              const dayKey = log.id.slice(0, 8);
              let list = beforeIdStat.everyDayLogMap.get(dayKey);
              if (list == undefined) list = new Array<string>();
              list.push(afterTaskLogdata[i].id);
              beforeIdStat.everyDayLogMap.set(dayKey, list);
              // console.log("beforeIdStat.everyDayLogMap", beforeIdStat.everyDayLogMap);
              let takeTime = log.endTime - log.startTime;
              const takeTime2 = beforeIdStat.everyDayTakeTime.get(dayKey);
              if (takeTime2 !== undefined) takeTime += takeTime2;
              beforeIdStat.everyDayTakeTime.set(dayKey, takeTime);
              // console.log("beforeIdStat.everyDayLogMap", beforeIdStat.everyDayTakeTime);
              const monthKey = log.id.slice(0, 6);
              let month = beforeIdStat.everyMonthLogMap.get(monthKey);
              if (month === undefined) {
                month = new Array<string>();
                month.push(dayKey);
              }
              beforeIdStat.everyMonthLogMap.set(monthKey, month);
              // console.log("beforeIdStat.everyDayLogMap", beforeIdStat.everyMonthLogMap);
            }
            // 添加回忆
            this.addMemory(afterTaskLogdata, beforeIdStat);
            changeKey.add(key);
            // console.log("beforeIdStat", beforeIdStat);
            // this.changeKeys.push(key);
          }
        }
      }
    }
    if (changeKey.size > 0) this.changeKeys = [...changeKey];
    // console.log("changeTaskLogData2NewTaskId",this.changeKeys)
  }
}
